
package com.netease.xone.fragment;

import java.util.Timer;
import java.util.TimerTask;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import android.app.Service;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.netease.pkgRelated.XoneConsts.BUNDLE_KEY;
import com.netease.pkgRelated.XoneConsts.INPUT_CELLPHONE_TYPE;
import com.netease.util.EnctryUtil;
import com.netease.xone.R;
import com.netease.xone.app.XoneApp;
import com.netease.xone.widget.EditTextWithClear;

public class FragCellPhoneInputCaptcha extends FragCellPhoneBase {

    private int mAction;
    private String mPhoneNum;

    private TextView mTvDesc;
    private EditText mEditCaptcha;
    private TextView mTvResend;
    private TextView mTvResendCountDownTimer;
    private Button mButtonNext;
    private FragmentManager mFragmentManager;

    private int mTitleResId;
    private int mTransactionId;
    private String mCaptchaVerify;

    public static FragCellPhoneInputCaptcha newInstance(int type, String phonenum) {
        FragCellPhoneInputCaptcha fragment = new FragCellPhoneInputCaptcha();
        Bundle b = new Bundle();
        b.putInt(BUNDLE_KEY.CELLPHONE_TYPE, type);
        b.putString(BUNDLE_KEY.CELLPHONE_NUMBER, phonenum);
        fragment.setArguments(b);
        return fragment;
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mTvResendCountDownTimer.setText(String.format("00:%02d", millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            mTvResendCountDownTimer.setVisibility(View.GONE);
            mTvResend.setTextColor(getResources().getColor(R.color.white));
            mTvResend.setClickable(true);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(BUNDLE_KEY.CELLPHONE_TYPE)
                && bundle.containsKey(BUNDLE_KEY.CELLPHONE_NUMBER)) {
            mAction = bundle.getInt(BUNDLE_KEY.CELLPHONE_TYPE);
            mPhoneNum = bundle.getString(BUNDLE_KEY.CELLPHONE_NUMBER);
        }
        if (mAction == INPUT_CELLPHONE_TYPE.Register) {
            mTitleResId = R.string.cellphoneRegister;
        } else {
            mTitleResId = R.string.findPassword;
        }
        if (!TextUtils.isEmpty(mPhoneNum)) {
            doGetCapthca();
        } else {
            showToast(R.string.phoneNumInvalid);
        }
        XoneService.getInstance().addListener(mXoneCallBack);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);

        getActivity().setTitle(mTitleResId);
        mFragmentManager = getFragmentManager();
        View view = inflater.inflate(R.layout.fragment_input_captcha, container, false);
        mTvDesc = (TextView)view.findViewById(R.id.inputCaptchaDesc);
        mTvDesc.setText(getString(R.string.inputCaptchaDesc1, mPhoneNum));
        mEditCaptcha = (EditTextWithClear)view.findViewById(R.id.inputCaptchaInput);

        mTvResendCountDownTimer = (TextView)view
                .findViewById(R.id.inputCaptchaResendCountDownTimer);
        mTvResend = (TextView)view.findViewById(R.id.inputCaptchaResend);
//        SpannableString ss = new SpannableString(getString(R.string.resend));
//        ss.setSpan(new UnderlineSpan(), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        mTvResend.setText(ss);
        mTvResend.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doGetCapthca();
            }
        });
        mTvResend.setClickable(false);
        mButtonNext = (Button)view.findViewById(R.id.cellphoneNextBtn);
        mButtonNext.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                doNext();
            }
        });
        return view;
    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        menu.add(0, MENU_ID.menu_cellphone_next2, 0, getActivity().getText(R.string.nextStep))
//                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//        super.onCreateOptionsMenu(menu, inflater);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == MENU_ID.menu_cellphone_next2) {
//            doNext();
//        }
//        return super.onOptionsItemSelected(item);
//    }

    private void doNext() {
        String captchaStr = mEditCaptcha.getText().toString();
        if (TextUtils.isEmpty(captchaStr)) {
            showToast(R.string.inputVerifyCodePrompt);
            return;
        }
        if (!EnctryUtil.getMd5Hash(captchaStr).equals(mCaptchaVerify)) {
            showToast(R.string.verifyCodeError);
            return;
        }
        Fragment frag = FragCellPhoneNickAndPw.newInstance(mAction, mPhoneNum, captchaStr);
        mFragmentManager.beginTransaction().replace(R.id.activity_CellPhone_container_id, frag)
                .addToBackStack(null).commit();
    }

    @Override
    public void onStart() {
        super.onStart();
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                if (getActivity() != null) {
                    InputMethodManager imm = (InputMethodManager)XoneApp.getAppInstance()
                            .getSystemService(Service.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(mEditCaptcha, 0);
                }
            }
        }, 300);
        mEditCaptcha.requestFocus();
    }
    @Override
    protected void onLeftTopBack() {
        getFragmentManager().popBackStack();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
        if(mCountDownTimer != null){
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    private void doGetCapthca() {
        // showWatting(getString(R.string.logining));
        mTransactionId = XoneService.getInstance().doGetCellphoneCaptcha(mAction, mPhoneNum);
    }

    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onGetCaptcha(int transactionId, String captcha) {
            // stopWaiting();
            mCaptchaVerify = captcha;
            showToast(R.string.sendVerifyCodeSuccess);
            mTvResendCountDownTimer.setVisibility(View.VISIBLE);
            mTvResend.setClickable(false);
            mTvResend.setTextColor(0xff999999);
            mCountDownTimer.start();
        };

        @Override
        public void onGetCaptchaError(int transactionId, int errCode, String err) {
            if (mTransactionId == transactionId) {
                // stopWaiting();
                if (errCode == XoneServiceCode.LOGINREG_ERR_MOBILE_MESSAGE_COUNT_EXCEED) {
                    mTvResend.setClickable(false);
                    mTvResend.setTextColor(0xff999999);
                }
                if (XoneServiceCode.LOGINREG_ERR_XONE_USERNONE == errCode) {
                    showToast(R.string.user_not_reg);
                } else {
                    showToast(err);
                }
            }

        };
        @Override
        public void onModifyCellPhonePw(int transactionId) {
            getFragmentManager().popBackStack();
        };
    };
}
